#include "TcpServer.hpp"
#include <memory>

static Response calculator(const Request &req)
{
    Response resp(0, 0);
    switch (req.op_)
    {
    case '+':
        resp.result_ = req.x_ + req.y_;
        break;
    case '-':
        resp.result_ = req.x_ - req.y_;
        break;
    case '*':
        resp.result_ = req.x_ * req.y_;
        break;
    case '/':
        if (0 == req.y_)
            resp.code_ = 1;
        else
            resp.result_ = req.x_ / req.y_;
        break;
    case '%':
        if (0 == req.y_)
            resp.code_ = 2;
        else
            resp.result_ = req.x_ % req.y_;
        break;
    default:
        resp.code_ = 3;
        break;
    }
    return resp;
}

void Network(Connection *con, string &request)
{
    logMessage(DEBUG, "application deaing...");
    // 反序列化
    Request req;
    if (!req.Deserialized(request))
        return;
    // 业务处理
    Response resp = calculator(req);
    // 序列化/应答
    string sender = resp.Serialize();
    sender = Encode(sender);
    // 发给服务器
    con->_out_buff += sender;
    // 让TcpServer底层发送
    // 开启EPOLLOUT，就会触发发送接口
    con->_tsvr->EnableReadWrite(con, true, true); // 回执指针为了使写关心打开
}

int main()
{
    unique_ptr<TcpServer> svr(new TcpServer);
    svr->Dispatcher(Network);
    return 0;
}